package com.itheima.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.tanhua.autoconfig.properties.OssProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class OssTemplate {

    @Value("${tanhua.oss.accessKey}")
    private String accessKeyId;

    @Value("${tanhua.oss.secret}")
    private String accessKeySecret;

    @Value("${tanhua.oss.bucketName}")
    private String bucketName;

    @Value("${tanhua.oss.url}")
    private String url;

    @Value("${tanhua.oss.endpoint}")
    private String endpoint;

    public OssTemplate(OssProperties properties) {
    }

    public String upload(String suffixName, InputStream is) {
        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + "." + suffixName;

        System.out.println(filename);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.putObject(bucketName, filename, is);

        ossClient.shutdown();

        String ossUrl = url + "/" + filename;

        System.out.println(ossUrl);

        return ossUrl;
    }
}